#include <stdio.h>
#include <string.h>
#include "mosquitto.h"
#include "cJSON.h"


int pack_json(char *buf,int size,char *id,float *temp,char *timep);



//int main()
int mosq_pub(struct mosquitto *mosq,char *topic,char *buf,int *qos)
{
	char		*rpi_id="rpi_001";
	char		*time="2023-4-19";
	float		temp=22.3;
	int       	rv=-1;
	char*           str;
	int		mid;

#if 0
	pack_json(buf,1024,rpi_id,&temp,time);
	printf("Json string:%s\n",buf);
#endif
	cJSON*          cjson_msg = NULL;
	cJSON* 		cjson_params = cJSON_CreateObject();

	cjson_msg = cJSON_CreateObject();

	cJSON_AddNumberToObject(cjson_params,"CurrentTemperature",temp);
	cJSON_AddItemToObject(cjson_msg,"params",cjson_params);

	str = cJSON_Print(cjson_msg);


//	rv=mosquitto_publish(mosq,NULL,topic,1024,buf,0,NULL);
	rv=mosquitto_publish(mosq,&mid,topic,strlen(str)+1,str,0,true);

	printf("Publish completed!\n");
	if(rv<0)
	{
		printf("Publish failure:%s\n",mosquitto_strerror(rv));
	}
}

int pack_json(char *buf,int size,char *id,float *temp,char *timep)
{
	cJSON *root = NULL;
	if(!buf || size<=0 || !id)
	{
		printf("Invalid input arguments\n");
		return -1;
	}

	root = cJSON_CreateObject();

	cJSON_AddItemToObject(root, "id",cJSON_CreateString(id));
	cJSON_AddStringToObject(root,"time",timep);
	cJSON_AddNumberToObject(root,"temperature",*temp);

	//strncpy(buf,cJSON_Print(root),size);   //将数据拷贝到buf中去
	buf = cJSON_Print(root);


	cJSON_Delete(root);

	return 0;
}
